﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Model;
using Aioms.Models;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Aioms.Controllers
{
    /// <summary>
    /// 测试类
    /// </summary>
    [DynamicApiController]
    public class OpLogController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public OpLogController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 日志列表
        /// </summary>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10) {
            RefAsync<int> total = 0;
            List<OpLog> opLogs = await db.Queryable<OpLog>().Where(ol => ol.Eid == eid).Where(ol => ol.Created.Date >= begintime.Date && ol.Created.Date <= endtime.Date).OrderBy("id desc").ToPageListAsync(pageIndex, pageSize, total);
            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = opLogs,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 生成日志
        /// </summary>
        /// <param name="oplog"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] OpLog oplog)
        {
            await db.Insertable<OpLog>(oplog).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
